package com.ruoyi.framework.dataScope;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.dataScope.strategy.DataScopeContext;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Order(90)
@Slf4j
@Data
@Intercepts({@Signature(type= StatementHandler.class,method="prepare",args = {Connection.class,Integer.class})})
@Component
public class DataAuthInterceptor extends AbstractSqlParserHandler implements Interceptor {
    @Autowired
    private DataScopeContext dataScopeContext;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        this.sqlParser(metaObject);
        // 判断是否为SELECT操作
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        //获取执行的sql语句
        String originalSql = boundSql.getSql();
        //获取sql语句的执行参数
        Object parameterObject = boundSql.getParameterObject();
        //查看参数中是否包含DataScope类型的参数
        DataAuth dataScope = findDataScopeObject(parameterObject);
        if (ObjectUtil.isNull(dataScope)) {
            return invocation.proceed();
        }
        String scopeCloumn=dataScope.getScopeColumn();
        List<Long> deptIds=dataScope.getDeptIds();
        if (CollUtil.isEmpty(deptIds)) {
            SysUser user = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest()).getUser();
            if (user == null) {
                if (user.isAdmin()) {
                    return invocation.proceed();
                } else {
                    throw new CustomException("请设置用户的数据权限");
                }
            }
            List<SysRole> roles = user.getRoles();
            if (CollUtil.isEmpty(roles)) {
                throw new CustomException("请为用户分配角色");
            }
            for (SysRole role :roles) {
                String scopeType = role.getDataScope();
                if (DataAuthConstant.DATA_SCOPE_ALL.equals(scopeType)) {
                    return invocation.proceed();
                }
                List<Long> deptIdsForDataScope = dataScopeContext.getDeptIdsForDataScope(role, scopeType);
                deptIds.addAll(deptIdsForDataScope);
            }
            String join = CollUtil.join(deptIds,",");
            originalSql = "select * from (" + originalSql + ") as temp_data_scope where temp_data_scope." + scopeCloumn + " in (" + join + ")";
            metaObject.setValue("delegate.boundSql.sql",originalSql);
            return invocation.proceed();
        }
        return invocation.proceed();
    }

    /**
     * 生成拦截对象的代理
     *
     * @param target 目标对象
     * @return 代理对象
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    /**
     * mybatis配置的属性
     *
     * @param properties mybatis配置的属性
     */
    @Override
    public void setProperties(Properties properties) {

    }

    private DataAuth findDataScopeObject(Object parameterObj) {
        if (parameterObj instanceof DataAuth) {
            return (DataAuth) parameterObj;
        } else if (parameterObj instanceof Map) {
            for (Object val :((Map<?,?>) parameterObj).values()) {
                if (val instanceof DataAuth) {
                    return (DataAuth) val;
                }
            }
        }
        return null;
    }

}
